package com.livepan.server.utils;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;

import java.io.File;

public class CosUtil {

    private static CosUtil cosUtil;
    // 1 初始化用户身份信息（secretId, secretKey）。

    public static CosUtil getInstance() {
        if (cosUtil == null) {
            synchronized (CosUtil.class) {
                if (cosUtil == null) {
                    cosUtil = new CosUtil();
                    cosUtil.init();
                }
            }
        }
        return cosUtil;
    }

    private COSCredentials cred;
    private Region region;
    private ClientConfig clientConfig;
    private COSClient cosClient;

    private void init() {
        cred = new BasicCOSCredentials(ConstUtil.secretId, ConstUtil.secretKey);
        // 2 设置 bucket 的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        region = new Region("ap-guangzhou");
        clientConfig = new ClientConfig(region);
        //设置https
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 3 生成 cos 客户端。
        cosClient = new COSClient(cred, clientConfig);
    }

    private CosUtil() {
    }


    //key :指定要上传到 COS 上对象键
    private synchronized static void uploadFile(String filePath, String key) {
        // 指定要上传的文件
        File localFile = new File(filePath);
        // 指定要上传到的存储桶
        String bucketName = "question-1254930541";
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
        PutObjectResult putObjectResult = getInstance().cosClient.putObject(putObjectRequest);
    }

    public static synchronized void uploadAvatar(String filePath, String key) {
        uploadFile(filePath, key);
    }
}
